package com.lance.answer.question_export;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * <p>以老师的身份获取答案<p>
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class GetYingyuAnswerByTeacher {

    public static void login(WebDriver driver, String userName, String pwd) {
        WebElement agreeButton = driver.findElement(By.id("RememberLogin"));
        agreeButton.click();

        WebElement userNameInput = driver.findElement(By.id("username"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();
    }

    public static void main(String[] args) throws Exception {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://thome.ouchn.cn/";
        driver.get(url);
        Thread.sleep(10000);
//        String userName = "xj_zhishu15";
//        String pwd = "zsxy123456WY";
        String userName = "zsxypy_6";
        String pwd = "zsxypy_6";

        //       SUBJECT.put("04017","管理英语1");
        //   SUBJECT.put("04016","人文英语4");
//        String subjectName = "公司财务";
//        String subjectCode = "00529";
//        String subjectName = "西方经济学（本）";
//        String subjectCode = "02307";
//        String subjectName = "管理英语4";
//        String subjectCode = "04020";

//        String subjectName = "数据库基础与应用";
//        String subjectCode = "01378";

//        String subjectName = "中国当代文学";
//        String subjectCode = "02015";

//        String subjectName = "药物治疗学";
//        String subjectCode = "02536";

        String subjectName = "理工英语3";
        String subjectCode = "04007";

        // fixme 2022-6-12
//        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-quiz.section");
//        List<String> list1 = IOUtils.readLines(inputStream3);
//        List<String> paths = new ArrayList<>();
//        for (String str : list1) {
//            paths.add(str.split(",")[0]);
//        }

        Set<String> paths = Sets.newHashSet();
        Set<String> urlTaskSet = Sets.newHashSet();
        File f1 = new File("libs//courseUrlInfo//"+subjectName+".txt");
        List<String> urlInfoList = IOUtils.readLines(new FileInputStream(f1), "utf-8");
        for (String urlInfo : urlInfoList) {
            if (urlInfo.contains("quiz")) {
                if (urlInfo.contains("形考")
                        || urlInfo.contains("作业")
                        || urlInfo.contains("专题测验")
                        || urlInfo.contains("专题检验")
                        || urlInfo.contains("单元自测")
                        //  || urlInfo.contains("测试（")
                        || urlInfo.contains("材料分析题（")
                        || urlInfo.contains("综合记分作业")
                ) {
                    if(urlInfo.contains("不计入")){
                        continue;
                    }
                    String urlTask = urlInfo.split(",")[0];
                    paths.add(urlTask);
                }
            }

        }


        login(driver, userName, pwd);

        Thread.sleep(1000);
        Util.switchToFirst(driver);
        //向下拉到底   driver.getMouse()
//        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,100000)");
//        Thread.sleep(6000);


        // driver.get("http://xinjiang.ouchn.cn/course/view.php?id=533");
        //  driver.navigate().to("http://xinjiang.ouchn.cn/course/view.php?id=533");
        //     Thread.sleep(5000);

        // ------------FIXME ----
//        for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
//                d -> d.findElements(By.tagName("a")))) {
//            if ("2".equals(we.getText())) {
//                we.click();
//                break;
//            }
//        }

        driver.findElement(By.id("txtclassname")).sendKeys(subjectName);
        driver.findElement(By.className("btnblue_m")).click();
        Thread.sleep(5000);


        for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.tagName("tr")))) {
            // 第一个TH是课程编号
            if (Util.findByTagName(we, "td") == null) {
                continue;
            }
            System.err.println("we.findElement(By.tagName(\"td\")).getText()):" + we.findElement(By.tagName("td")).getText());
            if (!subjectCode.equals(we.findElement(By.tagName("td")).getText())) {
                continue;
            }
            // 进入病理学与病理生理学
            we.findElement(By.tagName("a")).click();
            break;
        }
        Thread.sleep(5000);
        // ------------FIXME ----

        // 关闭其他页面，只留下当前课程页面
        Util.switchToFirst(driver);
        driver.close();
        Thread.sleep(2000);
        Util.switchToFirst(driver);
        List<Question> questions = Lists.newArrayList();
        // FIXME 如果标题相同就判断不出来了
      //  Set<String> titleSet = Sets.newHashSet();
        Map<String, String[]> titleMap = Maps.newHashMap();
        for (String urlTask : paths) {
            driver.get(urlTask);
            Thread.sleep(5000);
            // Util.switchToLast(driver);
            driver.findElement(By.className("quizattemptcounts")).findElement(By.tagName("a")).click();
            Thread.sleep(5000);
            // 回顾试答
            // reviewlink
            List<WebElement> infoList = new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                    d -> d.findElements(By.cssSelector("a[class='reviewlink']")));
            int infoSize = infoList.size();
            if(infoSize>5){
                infoSize = 5;
            }
            for (int i = 0; i < infoSize; i++) {
                new WebDriverWait(driver, Duration.ofSeconds(30)).until((ExpectedCondition<List<WebElement>>)
                        d -> d.findElements(By.cssSelector("a[class='reviewlink']"))).get(i).click();
                // FIXME TODO 获取题目信息




                for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                    if (null == singleSubject) {
                        continue;
                    }
                    String answerClass = singleSubject.getAttribute("class");
                    // informationitem  description description
                    if (Strings.isNullOrEmpty(answerClass)) {
                        continue;
                    }
                    if (answerClass.contains("description") || answerClass.contains("informationitem")) {
                        continue;
                    }
                    Question question = new Question();
                    question.setAnalyze("无");
                    question.setDifficult(1);
                    question.setGradeLevel(21);

                    String questionId = singleSubject.getAttribute("id");
                    // 这里的questionId是题目的ID
                    System.err.println("questionId:" + questionId);
                    WebElement contentElement = singleSubject.findElement(By.className("content"));

                    WebElement hiddenElement = singleSubject.
                            findElement(By.cssSelector("input[type='hidden']"));
                    // 题干
                    String name = hiddenElement.getAttribute("name");
                    System.err.println("name:" + name);
                    // qtext
                    // 题目标题
               //     String title = Util.getTitle(contentElement);
                 // formulation clearfix
                    String title ="";
                    try{
                     //   WebElement qTitleElement = contentElement.findElement(By.className("qtext"));
                        WebElement qTitleElement = Util.findByClassName(contentElement,"qtext");
                        if(null == qTitleElement){
                            qTitleElement =  contentElement.findElement(By.cssSelector("div[class='formulation clearfix']"));
                        }
                        title = Util.dealContent(qTitleElement.getText());
                    }catch (Exception e){
                        // 如果没有qtext 判断是填空题：获取全量：
                         contentElement.getText();
                    }
                    question.setTitle(title);

                    // FIXME
//                    if (titleSet.contains(title)) {
//                        continue;
//                    }
                    if (titleMap.get(title)!=null&&titleMap.get(title).length>0 && !answerClass.contains("que match deferredfeedback")) {
                        continue;
                    }
                    // 题目提示 tip prompt
                    WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                    if (null != promptElement) {
                        System.err.println("promptElement:" + promptElement.getText());
                    }

                    WebElement answerElement = Util.findByClassName(contentElement, "answer");
                    String labelType = "";
                    List<Item> items = Lists.newArrayList();
                    if (null != answerElement) {
                        // 找到每一个选项
                        // 针对多选和单选和判断题
                        for (WebElement singleAnswerElement : answerElement.
                                findElements(By.cssSelector("div[class^='r0'],div[class^='r1']"))) {

                            // 答案的序号 判断题没有序号 多选和单选有序号
                            String answerNumber = "";
                            WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                            if (numberElement != null) {
                                answerNumber = numberElement.getText();
                            }
                            // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                            String answerContent = Util.getAnswer(singleAnswerElement);
                            // 找到单选框或复选框
                            WebElement checkboxElement = singleAnswerElement.
                                    findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                            labelType = checkboxElement.getAttribute("type");
                            // 这里的ID是每个选项的ID
                            // answerContent是每个选项的内容
                            Item item = new Item();
                            item.setPrefix(answerNumber);
                            item.setContent(answerContent);
                            if (Strings.isNullOrEmpty(answerContent)) {
                                item.setPrefix(answerContent);
                            }
                            items.add(item);
                        }
                    }

                    if (answerClass.contains("multianswer")) {
                        question.setQuestionTypeDesc("完形填空");
                        question.setQuestionType(6);
                        System.err.println("1111111111111111111"+question);
                    }

                    // 获取正确答案
                    WebElement rightAnswer = Util.findByClassName(singleSubject, "rightanswer");
                    if (rightAnswer != null) {
                        //     String[] correctArray = new String[]{rightAnswer.getText()};
                        String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                        question.setCorrectArray(correctArray);
                    }else {
                        rightAnswer = Util.findByClassName(singleSubject,"generalfeedback");
                        if (rightAnswer != null) {
                           // String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                            String[] correctArray = new String[]{rightAnswer.getText()};
                            question.setCorrectArray(correctArray);
                        }
                    }
                    question.setItems(items);
                //    titleSet.add(question.getTitle());
                    titleMap.put(question.getTitle(),question.getCorrectArray());
                    //     questions.add(question);

                    // 简单题que essay manualgraded notyetanswered
                    if (answerClass.contains("essay")) {
                        // 等于选项的ID
                        question.setQuestionType(5);
                        question.setQuestionTypeDesc("简答题");
                        question.setCorrect("简单题");
                        questions.add(question);
                    }
                    // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                    if (answerClass.contains("truefalse")) {
                        question.setQuestionType(3);
                        question.setQuestionTypeDesc("判断题");
                        questions.add(question);
                    }
                    // 填空题 que shortanswer deferredfeedback notyetanswered
                    if (answerClass.contains("shortanswer")) {
                        WebElement textElement = contentElement.findElement(By.cssSelector("input[type='text']"));
                        String id = textElement.getAttribute("id");
                        // 等于选项的ID
                        question.setQuestionType(4);
                        question.setQuestionTypeDesc("填空题");
                        questions.add(question);
                    }
                    // 多选|单选：que multichoice deferredfeedback notyetanswered
                    if (answerClass.contains("multichoice")) {
                        if ("radio".equals(labelType)) {
                            question.setQuestionType(1);
                            question.setQuestionTypeDesc("单选题");
                            questions.add(question);
                        }
                        if ("checkbox".equals(labelType)) {
                            question.setQuestionType(2);
                            question.setQuestionTypeDesc("多选题");
                            questions.add(question);
                        }
                    }
                    if (answerClass.contains("multianswer")) {
                        questions.add(question);
                    }

                    if (answerClass.contains("ddwtos")) {
                        // 等于选项的ID
                        question.setQuestionType(10);
                        question.setQuestionTypeDesc("ddwtos");
                        questions.add(question);
                        WebElement rightAnswer222 = Util.findByClassName(singleSubject, "rightanswer");
                        if (rightAnswer != null) {
                            //     String[] correctArray = new String[]{rightAnswer.getText()};
                            String[] correctArray = new String[]{Util.dealContent(rightAnswer222.getText())};
                            question.setCorrectArray(correctArray);
                        }
                    }

                    if (answerClass.contains("que match deferredfeedback") // 匹配题目
                    ) {
                        // 等于选项的ID
                        WebElement tableWe = contentElement.findElement(By.cssSelector("table[class='answer']"));

                        List<Item> items1 = Lists.newArrayList();
                        for(WebElement trWe:tableWe. findElements(By.cssSelector("tr[class='r0'],tr[class='r1']"))){
                            Item item = new Item();
                            item.setContent(trWe.findElement(By.cssSelector("td[class='text']")).getText());
                            items1.add(item);
                        }
                        question.setItems(items1);
                        question.setQuestionType(61);
                        question.setQuestionTypeDesc("填空题");
                        question.setCorrect("匹配题目");
                        //    question.setCorrect(contentElement.findElement(By.cssSelector("div[clas='rightanswer']")).getText());
                        questions.add(question);
                    }

                }
//                if (i > 1) {
//                    break;
//                }
                Thread.sleep(5000);
                driver.navigate().back();
                Thread.sleep(2000);
             //   break;

            }
            Thread.sleep(2000);
            //  driver.close();
            Util.switchToLast(driver);
            Thread.sleep(2000);

        }

        Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {

            String title = question.getTitle();
            title = Util.dealContent(title);
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("answerType", "click");

            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", title);
            answerMap.put("questionCode", MD5Utils.encode(subjectName + title));
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());

            answers.add(answerMap);
        }

        FileUtils.write(new File("d://" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");


        Thread.sleep(2000);
        driver.quit();
    }
}
